<!--
 * @Author: zhangyang
 * @Date: 2022-03-09 17:54:14
 * @LastEditTime: 2022-05-07 11:56:30
 * @Description: 高级表格组件
-->
<script lang="ts" setup>
import type { TableDataItem, TableHeadItemPro } from '@/typings/table';
import type { EnableWrite } from '@/typings/type';
import type { PaginationProps } from 'naive-ui';
import type { SortState } from 'naive-ui/lib/data-table/src/interface';
type Props = {
  tableHead?: TableHeadItemPro[];
  tableData?: TableDataItem[];
  page?: number;
  limit?: number;
  total?: number;
};
const props = withDefaults(defineProps<Props>(), {
  tableHead: () => [],
  tableData: () => []
});

type Emits = {
  (e: 'sortChange', options: SortState | SortState[] | null): void;
  (e: 'checkChange', keys: (string | number)[]): void;
  (e: 'expandChange', keys: (string | number)[]): void;
  (e: 'update:page', n: number): void;
  (e: 'update:limit', n: number): void;
  (e: 'pageChange'): void;
}
const emit = defineEmits<Emits>();

const pagination = reactive<EnableWrite<PaginationProps>>({
  page: props.page ?? 1,
  pageSize: props.limit ?? 10,
  itemCount: props.total ?? 0,
  pageSlot: 5,
  showSizePicker: true,
  showQuickJumper: true,
  pageSizes: [10, 20, 50, 100],
  prefix: (info) => h('span', `共 ${info.itemCount} 条`)
});

watchEffect(() => {
  pagination.itemCount = props.total;
});

const pageChange = (p: number) => {
  pagination.page = p;
  emit('update:page', p);
  emit('pageChange');
};
const pageSizeChange = (limit: number) => {
  pagination.pageSize = limit
  pagination.page = 1;
  
  emit('update:limit', limit);
  emit('update:page', 1);
  emit('pageChange');
};

</script>
<template>
  <NDataTable
    v-bind="$attrs"
    :columns="tableHead"
    :data="tableData"
    :pagination="total ? pagination : undefined"
    remote
    @update-checked-row-keys="(k: any) => $emit('checkChange', k)"
    @update-expanded-row-keys="(k: any) => $emit('expandChange', k)"
    @update-sorter="(options: any) => $emit('sortChange', options)"
    @update-page="pageChange"
    @update-page-size="pageSizeChange"
  ></NDataTable>
</template>